<template>

  <div class="container">
        <div class="search-bar">
            <div>
                <span>推荐 :</span>
                <el-select v-model="params.is_recommend">
                    <el-option
                            label="全部"
                            :value="-1">
                    </el-option>
                    <el-option
                            label="否"
                            :value="0">
                    </el-option>
                    <el-option
                            label="是"
                            :value="1">
                    </el-option>
                </el-select>
            </div>
            <div>
                <span>状态 :</span>
                <el-select v-model="params.status">
                    <el-option
                            label="全部"
                            :value="-1">
                    </el-option>
                    <el-option
                            label="待审核"
                            :value="0">
                    </el-option>
                    <el-option
                            label="已通过"
                            :value="1">
                    </el-option>
                    <el-option
                            label="已拒绝"
                            :value="2">
                    </el-option>
                </el-select>
            </div>
            <div class="search_300">
                <span>标题 :</span>
                <el-input v-model="params.keyword" placeholder="模糊搜索"></el-input>
            </div>
            <div class="btn-group">
                <el-button type="primary" @click="fetch">查询</el-button>
            </div>
            <div class="btn-right">
                <el-button type="primary" @click="() => add(undefined)" icon="el-icon-plus"><i class="iconfont icon-add"></i>添加</el-button>
            </div>
        </div>

        <div class="inside-box">
            
            <el-table
                  border
                  :data="items"
                  style="width: 100%">
                  <el-table-column
                    prop="id"
                    label="ID"
                    min-width="25">
                  </el-table-column>
                  <el-table-column
                    prop="type"
                    label="类型"
                    >
                    <template slot-scope="scope">
                        <el-tag type="success" v-if="scope.row.type === 1">供应</el-tag>
                        <el-tag type="info" v-if="scope.row.type === 2">需求</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="title"
                    label="名称"
                    >
                  </el-table-column>
                  <el-table-column
                    prop="image"
                    label="主图"
                    >
                    <template slot-scope="scope">
                        <img :src="scope.row.image.file_url" width="100">
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="category.name"
                    label="分类"
                    >
                  </el-table-column>
                  <el-table-column
                    prop="member.nickname"
                    label="发布人"
                    >
                  </el-table-column>
                  <el-table-column
                    prop="member.mobile"
                    label="发布人手机"
                    >
                  </el-table-column>
                  <el-table-column
                    prop="enquires_count"
                    label="对接申请数"
                    >
                  </el-table-column>
                  <el-table-column
                    prop="list_order"
                    label="排序"
                    >
                  </el-table-column>
                  <el-table-column
                    label="推荐"
                    >
                    <template slot-scope="scope">
                        <el-tag type="info" v-if="scope.row.is_recommend">推荐</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="审核"
                    >
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status===0"  @click="saveStatus(scope.row)">待审核</el-tag>
                        <el-tag type="success" v-if="scope.row.status===1">已通过</el-tag>
                        <el-tag type="danger" v-if="scope.row.status===2">已拒绝</el-tag>
                        <template v-if="scope.row.status === 0">
                            <!-- <el-button size="small" type="success" @click="agree(scope.row)">通过</el-button>
                            <el-button size="small" type="dagner" @click="reject(scope.row)">拒绝</el-button> -->
                        </template>
                    </template>
                  </el-table-column>

                  <el-table-column
                    prop="remark"
                    label="备注"
                    >
                  </el-table-column>

                  <el-table-column
                    prop="created_at"
                    label="发布时间"
                    >
                  </el-table-column>

                  <el-table-column
                    label="操作"
                    width="300">
                    <template slot-scope="scope">
                        <!-- <el-button type="success" size="small" icon="el-icon-view" @click="show(scope.row)">详情</el-button> -->
                        <el-button type="primary" size="small" icon="el-icon-edit-outline" @click="edit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" icon="el-icon-delete" @click="del(scope.row)">删除</el-button>

                      </template>
                  </el-table-column>
                </el-table>

                <el-pagination ref="listPage" background :current-page.sync="CurrentPage" :page-size="params.limit" :page-sizes="[10,20,50,100]" layout="total, sizes, prev, pager, next, jumper" :total="total" @current-change="SetPage" @size-change="SizeChange" />

        </div>

        <!--#类目表单弹框-->
        <el-dialog title="表单" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">

            <el-form-item label="类型">
              <el-radio-group v-model="form.type" @change="Categorys()">
                <el-radio-button :label="1">供应</el-radio-button>
                <el-radio-button :label="2">需求</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="推荐">
                <el-switch
                  v-model="form.is_recommend"
                  active-color="#13ce66"
                  inactive-color="#999999"
                  :active-value="1"
                  :inactive-value="0"
                  >
                </el-switch>
            </el-form-item>  

            <el-form-item label="排序" prop="list_order">
                <el-input type="number" v-model="form.list_order" style="width:200px"></el-input>
            </el-form-item>

            <el-form-item label="备注">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 8}"
                placeholder="请输入内容"
                  maxlength="200"
                  show-word-limit
                v-model="form.remark">
              </el-input>
               <span style="color:red">*备注 不能超过200个字</span>
              </el-form-item>

            <el-form-item label="分类">
              <el-select v-model="form.information_category_id" filterable placeholder="请选择" prop="information_category_id">
                  <el-option
                    v-for="item in cateGoryData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发布人">
              <el-select v-model="form.member_id" filterable placeholder="请选择">
                  <el-option
                    v-for="item in membersData"
                    :key="item.id"
                    :label="item.nickname"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="title">
                <el-input placeholder="请输入名称" v-model="form.title" style="width:280px"></el-input><span style="color:red">*15个字内显示效果最佳</span>
              </el-form-item>


            <el-form-item label="简介" prop="desc">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 5}"
              placeholder="请输入内容"
                maxlength="200"
                 show-word-limit
              v-model="form.desc">
            </el-input>
               <span class="class_tag_red">*简介 30个字显示效果最佳</span>
             <!-- <textarea ref="textarea" placeholder="请输入简介内容"  maxlength="200" :style="{'height': height,'width':width}" v-model="form.desc" class="textarea" ></textarea><span style="color:red">*30个字显示效果最佳</span> -->

            </el-form-item>
             <el-form-item label="主图">
               <image-upload :files.sync="files" :max="1" @change="uploadImgHandle" />
                    <p class="class_tag_red">图片尺寸，宽x高：686像素x300像素</p>
               </el-form-item>


               <el-form-item label="小程序分享主图">
               
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>

                    <p class="class_tag_red">图片尺寸，宽x高：5:4</p>
               </el-form-item>

            <el-form-item label="正文">                
              <!-- 图片上传组件辅助-->
              <editor :content="content" v-model="form.content" @textChange="getMsgFormSon"></editor>  
            </el-form-item>

            </el-form>
            <div style="text-align: center">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save('form')">确 定</el-button>
            </div>
        </el-dialog>

        <!--#详情-->
        <el-dialog title="详情" :visible.sync="showDialogVisible" width="50%" :close-on-click-modal="false">
            <div>
                <div v-html="showItem.content"></div>
            </div>
        </el-dialog>

      <el-dialog
        title="提示"
        :visible.sync="checkStatus"
        width="30%"
        center>
        <span>请选择审核状态</span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="agree()">通过</el-button>
          <el-button  type="danger" @click="reject()">拒绝</el-button>
        </span>
      </el-dialog>
  </div>
</template>
<style scoped="scoped">
.search-bar {
  overflow: hidden;
  margin-bottom: 10px
}

.search-bar > div {
  float: left;
  margin-right: 10px;
  margin-top: 10px;
  overflow: hidden
}

.search-bar > .btn-group {
  float: left
}

.search-bar > .btn-right {
    float: right;
    margin-right: 0;
    overflow: hidden
}

.search-bar > div > span {
  font-size: 14px;
  color: #7d7d7d
}

.search-bar > div > .el-select {
  width: auto;
}


.search-bar > .search_200 > .el-input {
    width: 200px
}

.search-bar > .search_300 > .el-input {
    width: 300px
}

.search-bar > .search_400 > .el-input {
    width: 400px
}

.search-bar > .search_600 > .el-input {
    width: 600px
}  
</style>
<script>

import { getInformation, updateInformation, delInformation ,storeInformation } from '@/api/information'
import { getCategory } from '@/api/informationCategory'
import { VueEditor } from 'vue2-editor'
import { getList,getMembers } from '@/api/member'
import Upload from '@/components/Upload/index'

import editor from '@/components/Zeditor/Quilleditor' //通用版富文本，上传是 file 非 base64
import "@/config.css";

export default {
    components: {
       VueEditor,
       'image-upload': Upload,
       editor
  
    },
    data() {
        return {
           uploadUrl:process.env.VUE_APP_BASE_API + '/upload',
            // 类目数据
            items: [],
            imageUrl:'',
            content:'',
            cateGoryData:[],
            membersData:[],
            total: 0,
            CurrentPage: 1,
            // 是否显示类目弹框
            dialogVisible: false,
            showDialogVisible: false,
            // 类目表单
            form: {
              type: 1,
            },
            files: [],
            loading: true,
            params: {
                limit: 10,
                offset: 0,
                keyword: '',
                status: -1,
                is_recommend: -1
            },
            // 当前编辑中的上级
            parent: {},
            showItem: {},
            imageUrl:'',//主图
            action:this.upload_image_url,//TODO 这里先这样定义
            checkStatus:false,
            id:'',
            height: '100px',
            width:'600px',

            rules: {
              title: [
                { required: true, message: '名称不能空', trigger: 'blur' },
                { min: 3, max: 40, message: '长度在 3 到 40 个字符', trigger: 'blur' },
              ],
              desc: [
                { required: true, message: '简介不能空', trigger: 'blur' },
                { min: 3, max: 200, message: '长度在 3 到 200 个字符', trigger: 'blur' },
              ]
              
            },
        
        }
    },
    created() {
        this.fetch();
        this.Categorys();
        this.members();
        // alert(this.upload_image_url)
    },
    methods: {
      //获取子组件的 富文本内容
      getMsgFormSon(data){
         this.form.content = data         
      },
        // 获取类目列表
        fetch() {
            this.loading = true;
            getInformation(this.params).then(res => {
                console.log(res.data)
                if (res.code === 0) {
                    this.items = res.data.items;
                    this.total = res.data.total;
                } else {
                    this.$message(res.data.msg);
                }
                this.loading = false;
            }).catch(_ => {
                this.$message('出错了T_T...请联系管理员');
                this.loading = false;
            })
        },
        //新增类目
        saveStatus(row){
          // console.log(row.id,'iiiiii');return;
            this.id = row.id
            this.checkStatus = true;
        },
        add(data) {
            this.parent = data;
            this.form = {
                list_order: 100
            };
            this.files = [];
            this.form.type  = 1;
            this.imageUrl = '';
            this.dialogVisible = true;
        },
        // 修改类目
        edit(item) {
            this.parent = item;
            console.log(item,'ooo');
            this.form.type = item.type
            //因为不同的类型，要不同的分类数据 by:lwl 请求接口
            getCategory(this.form).then(res => {
                console.log(res.data)
                if (res.code === 0) {
                    this.cateGoryData = res.data;
                    // this.form.type = '';
                } else {
                    this.$message(res.data.msg);
                }
                this.loading = false;
            }).catch(_ => {
                this.$message('出错了T_T...请联系管理员');
                this.loading = false;
            })
            // this.form.type  = '';
            this.form = {
                id: item.id,
                is_recommend: item.is_recommend,
                list_order: item.list_order,
                desc: item.desc,
                content: item.content,
                title: item.title,
                member_id: item.member_id,
                remark: item.remark,
                type: item.type,
                information_category_id: item.information_category_id //不知道为啥 匹配  id 不可以。。。。。
              
                
            };
            item.image.url = item.image.file_url;
            // alert(item.poster_image);
            if(item.poster_image){
                  this.imageUrl = item.poster_image.file_url;
            }else{
                  this.imageUrl = '';
            }
            // this.imageUrl = item.poster_image==true?item.poster_image.file_url:'';
            this.files = [item.image];
            this.dialogVisible = true;
            this.content = item.content;
        },

        show(item) {
            this.showItem = item;
            // this.imageUrl = 
            // console.log(item,'oooo');
            this.showDialogVisible = true;
        },

        // 删除icon
        del(data) {
            this.loading = true;
            this.$confirm('确定删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delInformation(data.id).then(res => {
                if (res.code === 0) {
                    this.fetch();
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                    this.loading = false;
                } else {
                    this.$message.error(res.data.msg)
                    this.loading = false;
                }
            }).catch(_ => {
                this.loading = false;
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            })
            })
        },
        // 保存类目，根据form是否存在id字段，区别新增或修改保存
        save(formName) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                if(this.form.id){
                  this.update(this.form);
                }else{
                  console.log(this.form,'adfadfasdfasdf');
                  this.store(this.form);
                }
              } else {
                console.log('error submit!!');
                return false;
              }
          });            
        },
        agree() {
            this.update({id: this.id, status: 1});
            this.checkStatus = false;
        },
        reject() {
            this.update({id: this.id, status: 2});
            this.checkStatus = false;
        },
        //分类 by：lwl
        Categorys(){
            this.form.information_category_id = '',
            this.cateGoryData = [];
            getCategory(this.form).then(res => {
                console.log(res.data)
                if (res.code === 0) {
                    this.cateGoryData = res.data;
                } else {
                    this.$message(res.data.msg);
                }
                this.loading = false;
            }).catch(_ => {
                this.$message('出错了T_T...请联系管理员');
                this.loading = false;
            })
        },
        //获取所有所有用户列表
        members(){
            getMembers().then( response => {
              // console.log((response.data),'yy')
                this.membersData = (response.data);
            });
        },
        
        // 修改类目
        update(data) {
          // alert(this.form.information_category_id)
            this.loading = true; 
            updateInformation(data.id, data).then(res => {
                if (res.code === 0) {
                    this.dialogVisible = false
                    this.loading = false
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.fetch()
                } else {
                    this.$message.error(res.data.msg)
                    this.loading = false;
                }
            }).catch(_ => {
                this.$message('出错了T_T...请联系管理员');
                this.loading = false;
            })
        },
        //新增
        store(data) {
            delete data.image; //移除upload 组件对 form 新增的元素
            this.loading = true;
            if(!this.form.image_id){
                this.$message.error('请上传图片');
                return false;
            }
            storeInformation(data).then(res => {
                if (res.code === 0) {
                    this.dialogVisible = false
                    this.loading = false
                    this.fetch()
                } else {
                    this.$message.error(res.data.msg)
                    this.loading = false;
                }
            }).catch(_ => {
                this.$message('出错了T_T...请联系管理员');
                this.loading = false;
            })
        },

        SetPage(page) {
          this.params.offset = (page - 1) * this.params.limit
          this.fetch()
        },
        SizeChange(limit) {
          this.params.limit = limit
          this.params.CurrentPage = 1
          this.fetch()
        },
        uploadImgHandle(files, type) { // 上传图片
          if (typeof files[0] !== 'undefined') {
            const arr = [];
            files.forEach((element, index) => {
              const obj = {
                url: null,
                id: null
              }
              obj.url = element.file_url;
              obj.id = element.id;
              arr.push(obj)
            })
                this.form.image = arr[0];
    
                this.form.image_id = this.form.image.id;
                
                
            } else {
                this.form.image = null;
            }
        },
      handleAvatarSuccess(res, file) {
        this.form.poster_image_id = res.data.id;
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
        const isLt1M = file.size / 1024 / 1024 < 1;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt1M) {
          this.$message.error('上传头像图片大小不能超过 1MB!');
        }
        return isJPG && isLt1M;
      }

  
  

    }
}
</script>
